//
//  DetailMovieViewController.m
//  MyMovie
//
//  Created by lanou3g on 15/9/18.
//  Copyright (c) 2015年 HeQiangQiang. All rights reserved.
//

#import "DetailMovieViewController.h"
#import <MediaPlayer/MediaPlayer.h>
#import "PlayerDataBase.h"
#import "CommentTableViewController.h"

@interface DetailMovieViewController ()

@property (nonatomic, strong) MPMoviePlayerController *moviePlayer;//视频播放控制器
@property (nonatomic, strong) NSMutableArray *saveArray;

@end

@implementation DetailMovieViewController
- (NSMutableArray *)saveArray {
    if (!_saveArray) {
        _saveArray = [NSMutableArray array];
    }
    return _saveArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    UIBarButtonItem *rightBar = [[UIBarButtonItem alloc] initWithTitle:@"影评" style:(UIBarButtonItemStylePlain) target:self action:@selector(comment)];
    self.navigationItem.rightBarButtonItem = rightBar;
    
    [SVProgressHUD show];
    [self setUpDetailMovieWithJson];
    UIVisualEffectView *backVisual = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleDark]];
    backVisual.frame = self.view.bounds;
    backVisual.alpha = 1.0;
    [self.view addSubview:backVisual];
}
//跳转影评页面
- (void)comment {
    CommentTableViewController *view = [[CommentTableViewController alloc] init];
    view.popular_comments = [NSArray arrayWithArray:self.model.popular_comments];
    [self.navigationController pushViewController:view animated:YES];
}
- (void)setUpDetailMovieWithJson
{
    NSString *urlStr = [kDetailMovieUrl stringByReplacingOccurrencesOfString:@"电影ID" withString:self.willModel.ID];
    [LORequestManger GET:urlStr success:^(id response) {
        NSDictionary *dictionary = (NSDictionary *)response;
        self.model = [DetailModel setJsonWithDictionary:dictionary];
        
        [self setDetailMovieScrollView];
        [SVProgressHUD dismiss];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
}

- (void)setDetailMovieScrollView
{
    self.detailView = [[DetailMovieScrollView alloc] initWithFrame:CGRectMake(0, 64, kWidth, kHeight - 64 - 49)];
    [self.detailView setDetailViewWithDetailModel:self.model];
    [self.detailView setButtonClickWithTarget:self action:@selector(collectionButtonCilck:)];
    [self.detailView addTapLabelWithTarget:self action:@selector(actionTapMovieSummary:)];
    [self.view addSubview:self.detailView];
    
    for (int i = 0; i < self.model.trailer_urls.count; i++) {
        UIButton *button = (UIButton *)[self.detailView viewWithTag:1000 + i];
        [button addTarget:self action:@selector(button:) forControlEvents:(UIControlEventTouchUpInside)];
    }
    
//    NSString *string = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
//    NSString *string1 = [string stringByAppendingPathComponent:@"a.txt"];
    NSArray *array = [NSArray arrayWithArray:[[PlayerDataBase shareDataBase] selectFromTable:@"MyMovie"]];
    for (WillReleasedModel *willModel in array) {
        if ([self.model.title isEqualToString:willModel.title]) {
            self.detailView.collectionButton.selected = YES;
        }
    }
}
- (void)button:(UIButton *)bt {
    [self.moviePlayer.view removeFromSuperview];
    //视频文件路径
    NSString *path = self.model.trailer_urls[bt.tag-1000];
    //视频URL
    NSURL *url = [NSURL URLWithString:path];
    //视频播放对象
    self.moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:url];
    [bt addSubview:self.moviePlayer.view];
    self.moviePlayer.controlStyle = MPMovieControlStyleDefault;//视频外框样式
    self.moviePlayer.movieSourceType = MPMovieSourceTypeFile;
    [self.moviePlayer.view setFrame:CGRectMake(0, 0, kWidth, 300)];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(myMovieFinishedCallback:)
                                                 name:MPMoviePlayerPlaybackDidFinishNotification
                                               object:self.moviePlayer];
    
    [self.moviePlayer play];
}
-(void)myMovieFinishedCallback:(NSNotification*)notify {
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:MPMoviePlayerPlaybackDidFinishNotification
                                                  object:self.moviePlayer];
    [self.moviePlayer.view removeFromSuperview];
}
// 收藏按钮的点击事件
- (void)collectionButtonCilck:(UIButton *)button
{
    button.selected = !button.selected;
    if (button.selected) {
        [[PlayerDataBase shareDataBase] insertIntoTable:@"MyMovie" Model:self.willModel];
    } else {

        [[PlayerDataBase shareDataBase] deleteModelFromTable:@"MyMovie" WithSongID:self.willModel.ID];
    }
    
}

// 简介的点击事件
- (void)actionTapMovieSummary:(id)sender
{
    // 每次点击简介都改变frame（收缩简介）
    if (self.detailView.movieSummary.tag % 2 == 0) {
        NSString *str = self.model.summary;
        NSString *replaceStr = [str stringByReplacingOccurrencesOfString:@"©豆瓣" withString:@""];
        CGRect frame = [replaceStr boundingRectWithSize:CGSizeMake(kWidth - (20 * kFitWidth), 999) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:[NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:13.0] forKey:NSFontAttributeName] context:nil];
        self.detailView.movieSummary.frame = CGRectMake(10 * kFitWidth, 180 * kFitHeight, kWidth - (20 * kFitWidth), frame.size.height);
        self.detailView.movieSummary.text = replaceStr;
    }else {
        self.detailView.movieSummary.frame = CGRectMake(10 * kFitWidth, 180 * kFitHeight, kWidth - (20 * kFitWidth), 80 * kFitHeight);
    }
    self.detailView.movieSummary.tag += 1;
    
    // 重新设置导演和演员的scrollView的位置
    self.detailView.castsScrollView.frame = CGRectMake(0, self.detailView.movieSummary.frame.origin.y + self.detailView.movieSummary.frame.size.height + 20 * kFitHeight, kWidth, 160 * kFitHeight);
    // 重新设置所有控件的位置
    self.detailView.allView.frame = CGRectMake(0, self.detailView.castsScrollView.frame.origin.y + self.detailView.castsScrollView.frame.size.height + 20 * kFitHeight, kWidth, self.detailView.movieTrailerTitle.frame.origin.y + self.detailView.movieTrailerTitle.frame.size.height);
    // 重新设置详情界面scrollView的偏移范围
    self.detailView.contentSize = CGSizeMake(kWidth, self.detailView.allView.frame.origin.y + self.detailView.allView.frame.size.height);

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
